package com.teaching.Dao;

import com.teaching.Enity.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class StudentDaoAchieve implements StudentDao {

    private SqlSession sqlSession;
    private String resource = "mybatis.xml";

    @Override//查找所有学生
    public List<Student> findAllStudent() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sessionFactory.openSession();
        List<Student> studentList = sqlSession.selectList("findAllStudent");
        sqlSession.commit();
        sqlSession.close();
        return studentList;
    }

    @Override//按学号找学生
    public List<Student> findStudent(int id) throws IOException{
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sessionFactory.openSession();
        List<Student> studentList = sqlSession.selectList("findStudent",id);
        sqlSession.commit();
        sqlSession.close();
        return studentList;
    }

    @Override//查看选某一课程的学生
    public List<Student> findLearnStudent(int c_id) throws IOException{
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sessionFactory.openSession();
        List<Student> studentList = sqlSession.selectList("findLearnStudent",c_id);
        sqlSession.commit();
        sqlSession.close();
        return studentList;
    }

    @Override//更新数据库中学生密码
    public void modifyStudentPwd(Student student) throws IOException{
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sessionFactory.openSession();
        sqlSession.update("modifyStudentPwd",student);
        sqlSession.commit();
        sqlSession.close();
    }
}
